using Gtk;
using NHibernate;
using System;
using System.Collections;
using System.Reflection;

namespace Serpis
{
	internal class ComboBoxHelper
	{
		private ComboBox comboBox;
		private IList list;
		private Type type;
		private ListStore listStore;
		
		public ComboBoxHelper (ComboBox comboBox, Type type, string commandText)
		{
			this.comboBox = comboBox;
			this.type=type;
			ISession session=AppDbConnection.Instance.SessionFactory.OpenSession();
			IQuery query=session.CreateQuery(commandText);
			list=query.List();
			session.Close();
		}
		
		public object Id {
			get {
				if (listStore == null) 
					init(null);
				TreeIter treeIter;
				comboBox.GetActiveIter(out treeIter);
				return listStore.GetValue(treeIter, 0);
			}
			set {
				if (listStore == null) 
					init(value);
				else {
					TreeIter treeIter;
					if (!listStore.GetIterFirst(out treeIter))
						return;
					do {
						if (value.Equals(listStore.GetValue(treeIter, 0))) {
							comboBox.SetActiveIter(treeIter);
							break;
						}
					} while (listStore.IterNext(ref treeIter));
				}
			}
		}
		
		private void init (object id)
		{
			CellRendererText cellRendererText = new CellRendererText();
			comboBox.PackStart(cellRendererText, true);
			comboBox.AddAttribute(cellRendererText, "text", 1);
			listStore = new ListStore(type, typeof(string));
			TreeIter treeIter = listStore.AppendValues(null, "<vacio>");
			
			foreach (object obj in list) {
				string tag="";
				foreach (PropertyInfo pi in type.GetProperties())
				{
					if (pi.IsDefined(typeof(ShowAttribute),true))
					{
						tag=string.Concat(tag, pi.GetValue(obj,null).ToString());
					}
				}
				TreeIter currentTreeIter = listStore.AppendValues(obj, tag);
				if (obj == id)
					treeIter = currentTreeIter;
			}
			
			comboBox.Model = listStore;
			comboBox.SetActiveIter(treeIter);
			
			comboBox.Changed += delegate {
				raiseChanged();				
			};
		}
		
		private void raiseChanged()
		{
			if (Changed != null)
				Changed(this, EventArgs.Empty);
		}
		
		public event EventHandler Changed;
	}
}